package uk.ac.shef.ecomm.jdbc.mysql;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import uk.ac.shef.ecomm.*;

import uk.ac.shef.ecomm.*;

public class Utils extends mysqlDataAccess
{

	private PreparedStatement sqlCheckUser;
	private PreparedStatement sqlListRes;
	private PreparedStatement sqlListPart;
	
	public Utils()
	{
		try
		{
			connect();
			sqlCheckUser = connection.prepareStatement("SELECT * from "+ UserTBL + " where email=? and password=?");
			sqlListRes = connection.prepareStatement("SELECT * from "+ ResearchersTBL + " where email=?");
			sqlListPart = connection.prepareStatement("SELECT * from "+ ParticipantsTBL + " where email=?");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	public boolean Login(String email, String pass)
	{
		try
		{
			
			sqlCheckUser.setString(1, email);
			sqlCheckUser.setString(2, pass);
			
			ResultSet rset = sqlCheckUser.executeQuery();
			
			if (!rset.next()) 
			{
				return false;
			}
			else
			{
				return true;
			}
			
			
		}
		catch (SQLException sqle)
		{
			sqle.printStackTrace();
			return false;
		}
	}

	public Researcher getResDetails(String emailaddress)
	{
		try
		{
			
			sqlListRes.setString(1, emailaddress);
			
			ResultSet rset = sqlListRes.executeQuery();
			
			if (!rset.next()) {return null;}
			
			Researcher res = new Researcher();
			res.setEmail(rset.getString(1));
			res.setName(rset.getString(2));
			
			return res;
		}
		catch (SQLException sqle)
		{
			sqle.printStackTrace();
			return null;
		}
	
	}

	public Participant getPartDetails(String emailaddress)
	{
		try
		{
			
			sqlListPart.setString(1, emailaddress);
			
			ResultSet rset = sqlListPart.executeQuery();
			
			if (!rset.next()) {return null;}
			
			Participant res = new Participant();
			res.setEmail(rset.getString(1));
			res.setName(rset.getString(2));
			res.setDOB(rset.getDate(3));
			res.setGender(rset.getString(4));
			res.setLanguage(rset.getString(5));
			res.setIsSmoker(rset.getBoolean(6));
			
			return res;
		}
		catch (SQLException sqle)
		{
			sqle.printStackTrace();
			return null;
		}
	}

	public void close()
	{
		try
		{
			sqlCheckUser.close();
			sqlListRes.close(); 
			sqlListPart.close();
			connection.close();
		}
		catch (SQLException sqle)
		{
			sqle.printStackTrace();
		}
	}
}
